package jm.seamtest.beans;

import java.util.List;
import jm.seamtest.entities.User;

import org.hibernate.Query;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.faces.FacesMessages;

@Name("userBean")
@Scope(ScopeType.SESSION)
public class UserBean {
	@DataModel
	private List<User> users;
	private User user = new User();
	@DataModelSelection("users")
	private User selectedUser;
	private String verifyPassword;
	
	@In
	private Session seamDataBase;
	@In
	private FacesMessages facesMessages;
	
	public UserBean() {}
	
	@SuppressWarnings("unchecked")
	public void save() {
		if (user.getPassword().equals(verifyPassword)) {
			Query q = seamDataBase.createQuery("select u from User u where username like :username and id != :id");
			q.setParameter("username", user.getUsername());
			q.setParameter("id", user.getId());
			
			List existing = q.list();
			
			if (existing.size() == 0) {
				seamDataBase.saveOrUpdate(user);
				facesMessages.add("User was sucessfully saved !");
				user = new User();
			} else {
				facesMessages.addToControl("username", "The username "+user.getUsername()+" already exists !");
			}
		} else {
			facesMessages.addToControl("verify","Please retype your password !");
			verifyPassword = null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public void listUsers() {
		users = seamDataBase.createCriteria(User.class).list();
	}
	
	public void edit() {
		user = (User)seamDataBase.get(User.class, selectedUser.getId());
		facesMessages.add("Please after the changes, click on the save button !");
	}
	
	public void delete() {
		Object obj = seamDataBase.merge(selectedUser);
		seamDataBase.delete(obj);
		facesMessages.add("The user was successfully removed !");
	}
	
	public void newUser() {
		user = new User();
		facesMessages.add("Please, fill all fields and them press save !");
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(User selectedUser) {
		this.selectedUser = selectedUser;
	}

	public String getVerifyPassword() {
		return verifyPassword;
	}

	public void setVerifyPassword(String verifyPassword) {
		this.verifyPassword = verifyPassword;
	}

	public Session getSeamDataBase() {
		return seamDataBase;
	}

	public void setSeamDataBase(Session seamDataBase) {
		this.seamDataBase = seamDataBase;
	}

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

}
